﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace SqlQueryAnalyzer
{
    class AutoComplete
    {
        static string path = "SqlQueryAnalyzerAutoComplete.txt";
        public string Server { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }

        public static Dictionary<string, AutoComplete> GetAutoCompleteSource()
        {
            Dictionary<string, AutoComplete> autoDict = new Dictionary<string, AutoComplete>();
            if (File.Exists(path))
            {
                string[] configs = File.ReadAllLines(path).Select(c => Encrypt.Base64Decrypt(c)).ToArray();
                foreach (string config in configs)
                {
                    string[] temp = config.Split('|');
                    if (temp.Length == 3)
                    {
                        if (!autoDict.ContainsKey(temp[0].ToLower()))
                        {
                            autoDict.Add(temp[0].ToLower(), new AutoComplete()
                            {
                                Server = temp[0],
                                Username = temp[1],
                                Password = temp[2]
                            });
                        }
                    }
                }
            }
            return autoDict;
        }

        public static void SaveAutoCompleteSource(string server, string username, string password)
        {
            FileInfo fi = new FileInfo(path);
            if (fi.Exists && fi.Attributes != FileAttributes.Normal)
                fi.Attributes = FileAttributes.Normal;
            using (StreamWriter sw = fi.AppendText())
            {
                sw.WriteLine(Encrypt.Base64Encrypt(string.Format("{0}|{1}|{2}",server,username,password)));
            }
            fi.Attributes = FileAttributes.Hidden;

        }
    }
}
